package com.rem.cloudalibaba.controller;

import com.rem.cloudalibaba.entity.CommonResult;
import com.rem.cloudalibaba.entity.Product;
import com.rem.cloudalibaba.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author Rem
 * @date 2021-07-12
 */

@Slf4j
@RestController
@RefreshScope
public class ProductController {

    @Autowired
    ProductService productService;

    /**
     * 根据id查询商品
     *
     * @param id
     */
    @GetMapping("/product/getProduct/{id}")
    public CommonResult<Product> getProduct(@PathVariable("id") Integer id) {
        Optional<Product> optional = Optional.ofNullable(productService.findBuyId(id));
        return optional.map(CommonResult::ok).orElseGet(CommonResult::error);
    }

    /**
     * 扣减库存 返回商品详情
     *
     * @param id
     * @param num
     * @return
     */
    @PostMapping("/product/redStock/{id}/{num}")
    public CommonResult<Product> redStock(@PathVariable Integer id, @PathVariable Integer num) {
        Optional<Product> optional = Optional.ofNullable(productService.redStock(id, num));
        return optional.map(CommonResult::ok).orElseGet(CommonResult::error);
    }


    @GetMapping("/product/test/{id}")
    public CommonResult<String> test(@PathVariable("id") Integer id) {
        return CommonResult.ok("7001  test" + id);
    }


}
